/*
 * @Author: lyuan2018
 * @Date: 2019-08-08 10:57:10
 * @Last Modified by: lyuan2018
 * @Last Modified time: 2020-08-20 15:55:35
 * 邮件设置--账户管理--新建账户页面
 */
import React, { Component } from 'react';
import { inject, observer } from 'mobx-react';
import { toJS } from 'mobx';
import { Button, Steps, Modal, message } from 'antd';
import {
  WeaMoreButton,
  WeaLocaleProvider,
  WeaSearchGroup,
  WeaDialog,
  WeaHelpfulTip,
  WeaTagGroup,
  WeaError,
} from 'ecCom';
import { RenderForm } from '../util';
import { ResultPage } from './Result';
import { ExchangeResult } from './ExchangeResult';
import RenderChooseFolder from './RenderChooseFolderDialog';

const { Step } = Steps;
const getLabel = WeaLocaleProvider.getLabel;

@inject('settingStore')
@observer
class New extends Component {
  constructor(props) {
    super(props);
    this.prefixCls = 'email-setting-account-new';
    this.isExtra = props.isExtra || false;
    this.state = {
      autoGetFolderVisible: false,
      chooseFolders: [],
      autoGetFolderLoading: false,
      chooseFolderName: '',
    };
  }

  componentWillUnmount() {
    const {
      settingStore: { accountStore },
    } = this.props;
    accountStore.clear();
  }

  formChange = (data, change) => {
    // function just use in this page
    const {
      settingStore: { accountStore },
    } = this.props;
    const { newSecondFileds, newSecondForm } = accountStore;
    let option = Object.getOwnPropertyNames(data)[0];
    if (Object.prototype.hasOwnProperty.call(data, option)) {
      let value = data[option].value;
      let temp = newSecondFileds[0].items.find(
        item => item.domkey[0] === change,
      ); // if repeat use, please change the fields index to your need
      if (value === '0') {
        temp.viewAttr = 2;
        option === 'sendneedSSL' &&
          newSecondForm.updateFields({ smtpServerPort: { value: '25' } });
      } else if (value === '1') {
        temp.viewAttr = 1;
        option === 'sendneedSSL' &&
          newSecondForm.updateFields({
            smtpServerPort: { value: '465' },
            isStartTls: { value: '' },
          });
      }
    }
  };

  serverTypeChange = (data, form) => {
    let type = data.serverType.value;
    let getneedSSL = form.getFormParams().getneedSSL;
    if (type === '1') {
      form.updateFields({
        popServerPort: getneedSSL === '1' ? '995' : '110',
        popServer: '',
      });
    } else {
      form.updateFields({
        popServerPort: getneedSSL === '1' ? '993' : '143',
        popServer: '',
      });
    }
  };

  openIdentifyInvoiceChange = (data) => {
    let type = data.openIdentifyInvoice.value;
    if (type === '1') {
      Modal.info({
        title: getLabel(510826, '温馨提示'),
        content: (
          <div className="wea-list-confirm">
            <p style={{ 'font-weight': '700' }}>
              {getLabel(515692, '亲爱的用户，欢迎使用发票识别功能。')}
            </p>
            <p>
              {getLabel(
                515695,
                '1.为保证发票识别功能正常使用，我们会根据需要收集个人邮箱中公司指定发件人发送的发票信息，获取之后也仅作为用户及其公司在OA系统中的相关财务业务往来',
              )}
            </p>
            <p>
              {getLabel(
                515696,
                '2.我们非常重视您的隐私和个人信息保护，未经授权，不会私自收集、使用、共享您邮件中的个人信息，请放心使用',
              )}
            </p>
          </div>
        ),
        okText: getLabel(826, '确定'),
        onOk: () => {},
      });
    }
  };

  // 基本信息
  renderBasis = (form, fields) => {
    const { isFormInit } = form;
    let group = [];
    isFormInit &&
      fields &&
      fields.map((c) => {
        let items = [];
        c.items.map((field) => {
          if (field.domkey[0] === 'openIdentifyInvoice') {
            // 开启发票识别
            items.push({
              com: RenderForm(form, field, { style: { width: '100%' } }, '', {
                onChange: data => this.openIdentifyInvoiceChange(data, form),
              }),
            });
          } else {
            items.push({ com: RenderForm(form, field) });
          }
        });
        group.push(
          <WeaSearchGroup
            ecId={`${
              (this && this.props && this.props.ecId) || ''
            }_WeaSearchGroup@d79f22@${c.title}`}
            col={1}
            needTigger={true}
            showGroup={c.defaultshow}
            items={items}
          />,
        );
      });
    return group;
  };

  getneedSSLChange = (data, form) => {
    let getneedSSL = data.getneedSSL.value;
    let serverType = form.getFormParams().serverType;
    if (serverType === '2') {
      form.updateFields({ popServerPort: getneedSSL === '1' ? '993' : '143' });
    } else {
      form.updateFields({ popServerPort: getneedSSL === '1' ? '995' : '110' });
    }
  };

  // 服务器信息渲染
  renderService = (form, fields) => {
    const { isFormInit } = form;
    const {
      serverType,
      needSave,
      isReceiveSent,
      sentItems,
    } = form.getFormParams();
    let group = [];
    isFormInit &&
      fields &&
      fields.map((c, index) => {
        if (index === 0) {
          group.push(
            <WeaSearchGroup
              ecId={`${
                (this && this.props && this.props.ecId) || ''
              }_WeaSearchGroup@eux6ac@Service`}
              col={1}
              needTigger={true}
              showGroup={c.defaultshow}
              className={`${this.prefixCls}-service-group`}
            >
              {c.items.map((field) => {
                if (field.domkey[0] === 'serverType') {
                  if (serverType === '3') {
                    field = { ...field, ...{ labelcol: 14 } };
                  }
                  return RenderForm(
                    form,
                    field,
                    { style: { width: '50%' } },
                    '',
                    { onChange: data => this.serverTypeChange(data, form) },
                  );
                } else if (
                  field.domkey[0] === 'popServer' ||
                  field.domkey[0] === 'smtpServer'
                ) {
                  if (serverType !== '3') {
                    return RenderForm(form, field, { style: { width: '50%' } });
                  }
                } else if (field.domkey[0] === 'getneedSSL') {
                  if (serverType !== '3') {
                    return RenderForm(
                      form,
                      field,
                      { style: { width: '20%' } },
                      '',
                      { onChange: data => this.getneedSSLChange(data, form) },
                    );
                  }
                } else if (
                  field.domkey[0] === 'popServerPort' ||
                  field.domkey[0] === 'smtpServerPort'
                ) {
                  if (serverType !== '3') {
                    return RenderForm(form, field, { style: { width: '30%' } });
                  }
                } else if (
                  field.domkey[0] === 'ews_service_url' ||
                  field.domkey[0] === 'ews_domain' ||
                  field.domkey[0] === 'ews_version'
                ) {
                  if (serverType === '3') {
                    let newField = {
                      ...toJS(field),
                      fieldcol: 16,
                      labelcol: 7,
                    };
                    return RenderForm(form, newField, {
                      style: { width: '100%' },
                    });
                  }
                } else if (field.domkey[0] === 'sendneedSSL') {
                  if (serverType !== '3') {
                    return RenderForm(
                      form,
                      field,
                      { style: { width: '20%' } },
                      '',
                      {
                        onChange: data => this.formChange(data, 'isStartTls'),
                      },
                    );
                  }
                } else if (field.domkey[0] === 'needSave') {
                  // 保留服务器上的邮件
                  if (serverType !== '3') {
                    let helptip = (
                      <WeaHelpfulTip
                        ecId={`${
                          (this && this.props && this.props.ecId) || ''
                        }_WeaHelpfulTip@a2d881`}
                        title={getLabel(
                          510163,
                          '关闭后将删除邮箱服务器上的对应邮件，请谨慎设置！',
                        )}
                        placement="right"
                      />
                    );
                    let warningtip = (
                      <span style={{ color: 'red' }}>
                        {getLabel(
                          510163,
                          '关闭后将删除邮箱服务器上的对应邮件，请谨慎设置！',
                        )}
                      </span>
                    );
                    let needSaveSpan = needSave === '1' ? helptip : warningtip;
                    return RenderForm(
                      form,
                      field,
                      { style: { width: '100%' } },
                      needSaveSpan,
                      // {onChange: (data) => this.needSaveChange(data, form)}
                    );
                  }
                } else if (field.domkey[0] === 'isStartTls') {
                  if (serverType !== '3') {
                    return RenderForm(
                      form,
                      field,
                      { hideLabel: true, style: { width: '100%' } },
                      <span>
                        {getLabel(
                          129992,
                          '如果服务器支持，就使用STARTTLS加密传输',
                        )}
                      </span>,
                    );
                  }
                } else if (field.domkey[0] === 'needCheck') {
                  if (serverType !== '3') {
                    return RenderForm(form, field, {
                      style: { width: '100%' },
                    });
                  }
                } else if (field.domkey[0] === 'isReceiveSent') {
                  if (serverType === '3' || serverType === '2') {
                    return RenderForm(form, field, {
                      style: { width: '100%' },
                    });
                  }
                } else if (field.domkey[0] === 'sentItems') {
                  if (serverType === '2' && isReceiveSent === '1') {
                    return RenderForm(
                      form,
                      field,
                      { style: { width: '100%' } },
                      null,
                      {},
                      [
                        <WeaError
                          ecId={`${
                            (this && this.props && this.props.ecId) || ''
                          }_WeaError@10llkr@${field.domkey[0]}`}
                          tipPosition="bottom"
                          ref="sentItemsError"
                          error={getLabel('523072', '已发送文件夹名称未填写')}
                        >
                          <WeaTagGroup
                            ecId={`${
                              (this && this.props && this.props.ecId) || ''
                            }_WeaTagGroup@plohfr@${field.domkey[0]}`}
                            datas={Array.isArray(sentItems) ? sentItems : []}
                            type="emailOuterInput"
                            hasOps={false}
                            noSearch
                            onChange={(data) => {
                              const sentItemsValue =
                                data.length > 1
                                  ? [data[data.length - 1]]
                                  : data;
                              form.updateFields({
                                sentItems: { value: toJS(sentItemsValue) },
                              });
                            }}
                          />
                        </WeaError>,
                        <div className={`${this.prefixCls}-form-receiveSent`}>
                          <Button
                            ecId={`${
                              (this && this.props && this.props.ecId) || ''
                            }_Button@pd76ng@${field.domkey[0]}`}
                            onClick={this.onAutoGetFolderName}
                            loading={this.state.autoGetFolderLoading}
                          >
                            {getLabel('522596', '自动获取')}
                          </Button>
                        </div>,
                      ],
                    );
                  }
                } else {
                  return RenderForm(form, field, { style: { width: '100%' } });
                }
              })}
            </WeaSearchGroup>,
          );
        }
      });
    return group;
  };

  onAutoGetFolderName = () => {
    const {
      settingStore: { accountStore },
    } = this.props;
    const { newFirstForm, newSecondForm, onGetFolderName } = accountStore;
    const { popServer } = newSecondForm.getFormParams();
    const {
      accountMailAddress,
      accountPassword,
    } = newFirstForm.getFormParams();
    if (popServer.trim()) {
      let params = {
        mailuserAddress: accountMailAddress,
        mailuserPassword: accountPassword,
        imapServer: popServer,
      };
      this.setState({ autoGetFolderLoading: true }, async () => {
        try {
          let res = await onGetFolderName(params);
          if (res.getFolderStatus === '1') {
            let chooseFolders = res.sentItemNames.map((item, index) => ({
              key: index,
              showname: item.folderName,
              selected: false,
              isRec: item.isRec || false,
            }));
            this.setState({ chooseFolders, autoGetFolderVisible: true });
          } else {
            message.error(getLabel(522602, '获取失败，请重试！'));
          }
          this.setState({ autoGetFolderLoading: false });
        } catch (err) {
          this.setState({ autoGetFolderLoading: false });
        }
      });
    } else {
      Modal.warning({
        content: getLabel('522601', '请填写 接收邮件服务器 信息'),
      });
    }
  };

  needSaveChange = (data, form) => {
    let isSave = Object.getOwnPropertyNames(data)[0];
    if (Object.prototype.hasOwnProperty.call(data, isSave)) {
      let value = data[isSave].value;
      if (value * 1 === 0) {
        // 关闭
        Modal.confirm({
          title: getLabel(
            510162,
            '关闭后将删除邮箱服务器上的对应邮件，确定关闭？',
          ),
          okText: getLabel(826, '确定'),
          cancelText: getLabel(201, '取消'),
          onCancel: () => {
            form.updateFields({ needSave: { value: '1' } });
          },
        });
      }
    }
  };

  onChangeFolderName = (v) => {
    this.setState({ chooseFolderName: v });
  };

  onCancelAutoGetFolder = () =>
    this.setState({
      autoGetFolderVisible: false,
      chooseFolderName: '',
      autoGetFolderLoading: false,
    });

  onSetFolderName = () => {
    const {
      settingStore: { accountStore },
    } = this.props;
    const { newSecondForm } = accountStore;
    const { chooseFolderName, chooseFolders } = this.state;
    if (chooseFolderName.toString()) {
      let folderName = chooseFolders.filter(
        item => item.key === chooseFolderName,
      );
      folderName = folderName && folderName[0];
      folderName = (folderName && folderName.showname) || '';
      if (folderName) {
        newSecondForm.updateFields({
          sentItems: {
            value: [{ id: folderName, name: folderName, validate: true }],
          },
        });
        this.setState({ autoGetFolderVisible: false, chooseFolderName: '' });
      }
    } else {
      message.warning(getLabel('522597', '您还未选择文件夹！'));
    }
  };

  // 添加
  addAccount = (callback) => {
    const {
      settingStore: { accountStore },
    } = this.props;
    const { getNewAccountCondition } = accountStore;
    getNewAccountCondition(() => {
      if (callback && typeof callback === 'function') callback();
    });
  };

  // 页面退出
  onCancel = () => {
    const {
      settingStore: { accountStore },
      onCancel,
    } = this.props;
    const { setStoreState, newFirstForm, newSecondForm } = accountStore;
    setStoreState({ mailType: '', newStep: 0, isNewInit: true });
    window.e9HideFormFieldKeys = [];
    newFirstForm.resetForm();
    newSecondForm.resetForm();
    accountStore.clear();
    if (onCancel && typeof onCancel === 'function') onCancel();
  };

  stepChange = () => {
    const {
      settingStore: { accountStore },
      onSubmit,
    } = this.props;
    const { stepChange, newStep, newSecondForm } = accountStore;
    let formParams = newSecondForm.getFormParams();
    let flag = true;

    if (newStep * 1 === 1) {
      if (formParams.serverType === '2' && formParams.isReceiveSent === '1') {
        if (
          !formParams.sentItems ||
          (Array.isArray(formParams.sentItems) &&
            formParams.sentItems.length === 0)
        ) {
          this.refs.sentItemsError.showError();
          flag = false;
        }
      }
    }
    if (flag) {
      stepChange('', () => {
        if (onSubmit && typeof onSubmit === 'function') onSubmit();
      });
    }
  };

  toPreStep = () => {
    const {
      settingStore: { accountStore },
    } = this.props;
    const { newStep, setStoreState, nextLoading } = accountStore;
    if (!nextLoading) {
      setStoreState({
        newStep: newStep - 1,
        isNewInit: false,
        editResult: {},
      });
    }
  };

  toNextStep = () => {
    const {
      settingStore: { accountStore },
    } = this.props;
    const { nextLoading } = accountStore;
    if (!nextLoading) {
      this.stepChange();
    }
  };

  render() {
    const {
      settingStore: { accountStore },
      visible,
    } = this.props;
    const {
      newFirstForm,
      newFirstFileds,
      newStep,
      newSecondForm,
      newSecondFileds,
      validateLoading,
      editResult,
      mailType,
      nextLoading,
    } = accountStore;

    const buttons = [
      newStep !== 0 &&
        (toJS(editResult) == null ||
          (toJS(editResult) != null && !toJS(editResult).mailState)) && (
          <Button
            ecId={`${
              (this && this.props && this.props.ecId) || ''
            }_Button@ocrhkx@pre`}
            type="primary"
            loading={nextLoading}
            onClick={this.toPreStep}
          >
            {getLabel(1876, '上一步')}
          </Button>
        ),
      newStep !== 2 && (
        <Button
          ecId={`${
            (this && this.props && this.props.ecId) || ''
          }_Button@4elsaq@next`}
          type="primary"
          loading={nextLoading}
          onClick={this.toNextStep}
        >
          {getLabel(1402, '下一步')}
        </Button>
      ),
      newStep === 2 && (
        <Button
          ecId={`${
            (this && this.props && this.props.ecId) || ''
          }_Button@vhcg48@close`}
          type="primary"
          onClick={this.onCancel}
        >
          {getLabel(309, '关闭')}
        </Button>
      ),
      <WeaMoreButton
        ecId={`${
          (this && this.props && this.props.ecId) || ''
        }_WeaMoreButton@j5wk3k@more`}
      />,
    ];
    return (
      <WeaDialog
        ecId={`${
          (this && this.props && this.props.ecId) || ''
        }_WeaDialog@9wwgyt`}
        icon="icon-coms-email"
        iconBgcolor="#788f9d"
        title={getLabel(384433, '新建账户信息')}
        visible={visible}
        style={{ width: 714, height: 600 }}
        className={this.prefixCls}
        onCancel={this.onCancel}
        buttons={buttons}
        hasScroll
      >
        <Steps
          ecId={`${(this && this.props && this.props.ecId) || ''}_Steps@3v3ws4`}
          className={`${this.prefixCls}-stepbar`}
          current={newStep}
        >
          <Step
            ecId={`${
              (this && this.props && this.props.ecId) || ''
            }_Step@51gh5f`}
            title={getLabel(81711, '基本信息')}
          />
          <Step
            ecId={`${
              (this && this.props && this.props.ecId) || ''
            }_Step@gaa897`}
            title={getLabel(19806, '服务器信息')}
          />
          <Step
            ecId={`${
              (this && this.props && this.props.ecId) || ''
            }_Step@96gavd`}
            title={getLabel(82876, '检测结果')}
          />
        </Steps>
        <div className={`${this.prefixCls}-content`}>
          {newStep === 0 && this.renderBasis(newFirstForm, newFirstFileds)}
          {newStep === 1 && this.renderService(newSecondForm, newSecondFileds)}
          {newStep === 2 &&
            (mailType == 3
              ? ExchangeResult(validateLoading, editResult)
              : ResultPage(validateLoading, editResult, mailType))}
        </div>
        <RenderChooseFolder
          ecId={`${
            (this && this.props && this.props.ecId) || ''
          }_RenderChooseFolder@g8x3d2`}
          visible={this.state.autoGetFolderVisible}
          onCancel={this.onCancelAutoGetFolder}
          value={this.state.chooseFolderName}
          options={this.state.chooseFolders}
          onChangeFolderName={this.onChangeFolderName}
          onSubmit={this.onSetFolderName}
        />
      </WeaDialog>
    );
  }
}
export default New;

/*
  外部调用方式：
  visible: must 控制弹窗显隐
  onCancel: 取消/关闭弹窗回调
  onSubmit: 保存回调
  open方法： 通过ref调用addAccount(callback)
*/
